package lc.com.lcpicturebackend.manager.websocket.disruptor;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import jakarta.annotation.PreDestroy;
import lc.com.lcpicturebackend.manager.websocket.model.PictureEditRequestMessage;
import lc.com.lcpicturebackend.model.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import jakarta.annotation.Resource;

/**
 * 功能：事件生产者
 * 将事件放入到ringBuffer中,并提供优雅停机
 * 作者：lc
 * 日期：2025/4/28 16:39
 */
@Component
public class PictureEditEventProducer {

    @Resource
    private Disruptor<PictureEditEvent> disruptor;

    public void publicEvent(PictureEditRequestMessage pictureEditRequestMessage, WebSocketSession session,
                            User user,Long pictureId){
        RingBuffer<PictureEditEvent> ringBuffer = disruptor.getRingBuffer();
        long next = ringBuffer.next();
        PictureEditEvent pictureEditEvent = ringBuffer.get(next);
        pictureEditEvent.setPictureEditRequestMessage(pictureEditRequestMessage);
        pictureEditEvent.setWebSocketSession(session);
        pictureEditEvent.setUser(user);
        pictureEditEvent.setPictureId(pictureId);
        //发布事件
        ringBuffer.publish(next);
    }

    /**
     * 优雅停机
     */
    @PreDestroy
    public void shutdown(){
        disruptor.shutdown();
    }
}
